package com.uziot.bucket.common.queue;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author shidt
 * @version V1.0
 * @className BlockQueueTask
 * @date 2020-11-29 15:57:35
 * @description 阻塞队列任务
 */

@Slf4j
@RequiredArgsConstructor
public class BlockQueueTask {

    private final BlockingQueue<String> queue = new ArrayBlockingQueue<>(1024);

    /**
     * 保存文章的浏览记录，先进先出
     */
    public void addLookRecordToQueue(String articleLook) {
        if (null == articleLook) {
            return;
        }
        queue.offer(articleLook);
    }

    public void save() {
        List<String> bufferList = new ArrayList<>();
        while (true) {
            try {
                bufferList.add(queue.take());
                for (String articleLook : bufferList) {
                    log.debug("执行阻塞队列所有内容:{}", articleLook);
                }
            } catch (InterruptedException e) {
                log.error("保存文章浏览记录失败--->[{}]", e.getMessage());
                // 防止缓冲队列填充数据出现异常时不断刷屏
                try {
                    Thread.sleep(1000);
                } catch (Exception err) {
                    log.error(err.getMessage());
                }
            } finally {
                bufferList.clear();
            }
        }
    }


    public static void main(String[] args) {
        BlockQueueTask blockQueueTask = new BlockQueueTask();

        new Thread(() -> {
            blockQueueTask.save();;
        }).start();

        new Thread(() -> {
            blockQueueTask.addLookRecordToQueue("111111111");
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            blockQueueTask.addLookRecordToQueue("22222222");
        }).start();

        System.out.println("主线程结束");
    }
}
